/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.broker.controller;

import java.util.ArrayList;
import java.util.List;

import org.ourgrid.broker.BrokerConstants;
import org.ourgrid.broker.commands.CommandExecutor;
import org.ourgrid.broker.commands.SchedulerData;
import org.ourgrid.broker.controller.messages.LocalWorkerProviderClientMessages;
import org.ourgrid.broker.dao.JobDAO;
import org.ourgrid.broker.dao.PeerDAO;
import org.ourgrid.broker.dao.PeerEntry;
import org.ourgrid.broker.dao.WorkerDAO;
import org.ourgrid.broker.scheduler.SchedulerIF;
import org.ourgrid.common.LoginResult;
import org.ourgrid.common.interfaces.AccountingAggregator;
import org.ourgrid.common.interfaces.LocalWorkerProvider;
import org.ourgrid.common.interfaces.LocalWorkerProviderClient;
import org.ourgrid.common.interfaces.Worker;
import org.ourgrid.common.interfaces.to.RequestSpec;
import org.ourgrid.common.spec.worker.WorkerSpec;
import org.ourgrid.reqtrace.Req;

import br.edu.ufcg.lsd.commune.api.FailureNotification;
import br.edu.ufcg.lsd.commune.api.InvokeOnDeploy;
import br.edu.ufcg.lsd.commune.api.MonitoredBy;
import br.edu.ufcg.lsd.commune.api.RecoveryNotification;
import br.edu.ufcg.lsd.commune.container.servicemanager.ServiceManager;
import br.edu.ufcg.lsd.commune.identification.DeploymentID;
import br.edu.ufcg.lsd.commune.identification.ServiceID;

/**
 */
public class LocalWorkerProviderClientController implements LocalWorkerProviderClient {

	private ServiceManager serviceManager;

	@InvokeOnDeploy
	public void init(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}

	/**
	 * 
	 * @param workerProvider
	 * @param result
	 * @param peerAccounting
	 * @param string 
	 */
	@Req("REQ311")
	public void loginSucceed(
			@MonitoredBy(BrokerConstants.PEER_MONITOR_OBJECT_NAME)LocalWorkerProvider workerProvider,
			LoginResult result, 
			@MonitoredBy(BrokerConstants.LOCAL_WORKER_PROVIDER_CLIENT)AccountingAggregator peerAccounting) {
		
		String senderPubKey = serviceManager.getSenderPublicKey();
		DeploymentID peerDeploymentID = serviceManager.getStubDeploymentID(workerProvider);
		String peerPublicKey = peerDeploymentID.getPublicKey();
		
		if (!senderPubKey.equals(peerPublicKey)) {
			serviceManager.getLog().warn(LocalWorkerProviderClientMessages.getUnknownPeerSentALoginSucceedMessage(peerPublicKey));
			return;
		}
		
		PeerEntry peerEntry = serviceManager.getDAO(PeerDAO.class).getPeerEntry(
				peerDeploymentID.getContainerID());
		
		if (peerEntry == null) {
			serviceManager.getLog().warn(LocalWorkerProviderClientMessages.getUnknownPeerSentALoginSucceedMessage(peerPublicKey));
			return;
		}
		
		if (peerEntry.isDown()) {
			serviceManager.getLog().warn(LocalWorkerProviderClientMessages.getPeerDownLoginSucceedMessage(peerPublicKey));
			return;
		}
		
		if (peerEntry.isLogged()) {
			serviceManager.getLog().warn(LocalWorkerProviderClientMessages.getPeerLoggedLoginSucceedMessage(peerPublicKey));
			return;
		}
		
		if (result.hasAnErrorOcurred()) {
			serviceManager.getLog().warn(LocalWorkerProviderClientMessages.getErrorOcurredWhileLoggingIn(
					result.getErrorMessage(), peerPublicKey));
			return;
		}
		
		peerEntry.setAsLogged();
		
		List<SchedulerData> outputCommands = new ArrayList<SchedulerData>();
		
		for(SchedulerIF scheduler: getJobDAO().getSchedulers()) {
			List<SchedulerData> cjData = scheduler.loginSucceed(peerDeploymentID.toString());
			outputCommands.addAll(cjData);
		}
		
		CommandExecutor.getInstance().execute(outputCommands, serviceManager);
		
		serviceManager.getDAO(PeerDAO.class).addAccountingAggregator(
				peerDeploymentID.getContainerID(), peerAccounting);
	}
	
	private JobDAO getJobDAO() {
		return serviceManager.getDAO(JobDAO.class);
	}
	
	private WorkerDAO getWorkerDAO() {
		return serviceManager.getDAO(WorkerDAO.class);
	}

	@Req("REQ312")
	public void hereIsWorker(
			@MonitoredBy(BrokerConstants.WORKER_MONITOR_OBJECT_NAME) Worker worker, 
			WorkerSpec workerSpec, RequestSpec requestSpec) {
		
		String senderPublicKey = serviceManager.getSenderPublicKey();
		PeerEntry peerEntry = serviceManager.getDAO(PeerDAO.class).getPeerEntry(
				serviceManager.getSenderContainerID());
		
		DeploymentID workerDeploymentID = serviceManager.getStubDeploymentID(worker);
		if (peerEntry == null) {
			serviceManager.getLog().warn(LocalWorkerProviderClientMessages.getUnknownPeerDeliveredAWorkerMessage(
					workerDeploymentID.getPublicKey(), senderPublicKey));
			serviceManager.release(worker);
			return;
		}
		
		if (peerEntry.isDown()) {
			serviceManager.getLog().warn(LocalWorkerProviderClientMessages.getDownPeerDeliveredAWorkerMessage(
					workerDeploymentID.getPublicKey(), senderPublicKey));
			serviceManager.release(worker);
			return;
		}
		
		if (peerEntry.isUp()) {
			serviceManager.getLog().warn(LocalWorkerProviderClientMessages.getNotLoggedPeerDeliveredAWorkerMessage(
					workerDeploymentID.getPublicKey(), senderPublicKey));
			serviceManager.release(worker);
			return;
		}
		
		LocalWorkerProvider localWorkerProvider = peerEntry.getLocalWorkerProvider();
		
		getWorkerDAO().addWorker(workerDeploymentID, worker, workerSpec);

		DeploymentID peerID = serviceManager.getStubDeploymentID(localWorkerProvider);
		ServiceID workerServiceID = serviceManager.getStubDeploymentID(worker).getServiceID();
		
		if (requestSpec == null) {
			serviceManager.getLog().warn(LocalWorkerProviderClientMessages.nullRequestMessage(workerDeploymentID.getPublicKey(), 
					senderPublicKey));
			localWorkerProvider.disposeWorker(workerServiceID);
			serviceManager.release(worker);
			return;
		}	
		
		int jobID = getJobDAO().getJobForThisRequest(requestSpec.getRequestId());
		
		if (jobID == -1) {
			serviceManager.getLog().warn(LocalWorkerProviderClientMessages.getBrokerWithoutRunningJobsReceivingWorkerMessage(
					workerDeploymentID.getPublicKey(), senderPublicKey));
			localWorkerProvider.disposeWorker(workerServiceID);
			serviceManager.release(worker);
			return;
		}
		
		getJobDAO().addWorker2Job(workerDeploymentID.getServiceID().getContainerID().toString(), jobID);
		
		if (jobID > -1) {
			List<SchedulerData> outputCommands = new ArrayList<SchedulerData>();
			
			SchedulerIF scheduler = getJobDAO().getJobScheduler(jobID);
			List<SchedulerData> cjData = scheduler.hereIsWorker(workerDeploymentID.toString(), 
					workerDeploymentID.getPublicKey(), senderPublicKey, peerID.toString(),
					requestSpec, workerSpec);
			
			outputCommands.addAll(cjData);
		
			CommandExecutor.getInstance().execute(outputCommands, serviceManager);
		}
	}

	@RecoveryNotification
	public void accountingIsUp(AccountingAggregator accounting) {}
	
	@FailureNotification
	public void accountingIsDown(AccountingAggregator accounting) {}

}
